package com.neutech.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.neutech.entity.HomeWorkCommit;
import com.neutech.mapper.HomeWorkCommitMapper;
import com.neutech.service.HomeWorkCommitService;
import com.neutech.service.MinioService;
import jakarta.annotation.Resource;
import lombok.Data;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 作业提交表 服务层实现。
 *
 * @author Administrator
 * @since 2025-06-19
 */
@Service
public class HomeWorkCommitServiceImpl extends ServiceImpl<HomeWorkCommitMapper, HomeWorkCommit>  implements HomeWorkCommitService{

    @Resource
    MinioService minioService;
    @Value("${minio.endpoint}")
    String endpoint;
    @Value("${funasr.url}")
    String url;
    @Override
    public boolean add(MultipartFile file, HomeWorkCommit homeWorkCommit) throws Exception {
        homeWorkCommit.setPath(minioService.upload(file));
        return this.save(homeWorkCommit);
    }

    @Override
    public List<HomeWorkCommit> list(Integer homeWorkId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("home_work_id", homeWorkId);
        return this.list(wrapper);
    }

    @Override
    public boolean read(Integer id) throws IOException {
        HomeWorkCommit homeWorkCommmit = this.getById(id);
        String path = endpoint + "/" +homeWorkCommmit.getPath();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(5, TimeUnit.MINUTES);
        OkHttpClient client = builder.build();
        RequestBody formBody = new FormBody.Builder()
                .add("url", path)
                .build();
        Request request = new Request.Builder()
                .url(url) // 替换为你的API URL
                .post(formBody)
                .build();
        Response response = client.newCall(request).execute();
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseJson responseJson = objectMapper.readValue(response.body().string(), ResponseJson.class);
        homeWorkCommmit.setContent(responseJson.getContent());
        homeWorkCommmit.setVal(new BigDecimal(responseJson.getTime()));
        return this.updateById(homeWorkCommmit);
    }
    @Data
    private static class ResponseJson {
        private String content;
        private String time;
    }
}
